﻿

var mapJsonUrl = "../buswayline/map.json";

/**
 * 初始化，设置 线路下拉框信息
 */
var selLineNameShow = () => {

    // $.post("../Home/GetRouteCollect", function (data) {
    //     var item = "[" + data + "]";
    //     var data = JSON.parse(item);
    //    for(item of data){
    //        item.routePath = subLinePath(item.stopsOnRoute);
    //    }
    //     reloadSubWayLine(data);
    // })

    $.getJSON(mapJsonUrl, function (data) {
        mapJson = data;
        if (mapJson != "") {
            var html = "";
            mapJson.filter(function (item, index) {
                html += " <option value=" + item.displayName + ">" + item.displayName + "</option>";
            })
            $("#lineName,#virtualLineName,#arbitrarily_lineName").append(html);
        }
    });
}

var panelMove = false;
/**
 * 设置站点面板信息
 * @param {any} currentLine  当前线路
 * @param {any} subStation   操作站点信息
 */
var setStationPanel = (currentLine, subStation) => {
    demo1.setValue([]);
    $(".panel").show();
    elementDraggable("movePanel");
    $("#lineName").val(currentLine.displayName);
    $("#routeMapStopID").val(subStation.routeMapStopID);
    $("#stopChiName").val(subStation.stopChiName);
    $("#stopName").val(subStation.stopName);
    $("#stopX").val(subStation.stopX);
    $("#stopY").val(subStation.stopY);
    $("#offsetX").val(subStation.nameRight ?? 0);
    $("#offsetY").val(subStation.nameTop ?? 0);
    $("#colorPicker").val("#" + currentLine.routeColor);
    $("#exchangeStop").attr("checked", subStation.exchangeStop);

    if (subStation.virtualStop)
        $(".oper").hide();
    else
        $(".oper").show();

    stationCollection(currentLine);

    var movePanel = document.getElementById("movePanel");
    var mouseEnterHandler = () => {
        panelMove = true;
    }
    var mouseLeaveHandler = () => {
        panelMove = false;
    }
    movePanel.addEventListener("mouseenter", mouseEnterHandler);
    movePanel.addEventListener("mouseleave", mouseLeaveHandler);
}

/**
 * 修改站点信息
 * @param {string} lineName 线路名称
 * @param {string} routeMapStopID 编码
 * @param {string} stopChiName 名称
 * @param {string} stopName 英文名称
 * @param {int} stopX 站点 X 轴 
 * @param {int} stopY 站点 Y 轴
 * @param {int} offsetX text X 轴文字 
 * @param {int} offsetY text Y 轴文字
 * @param {string} lineColor 线路颜色
 * @param {boolean} isExchangeStop 是否为换乘站
 */
var updateMapStation = (lineName, routeMapStopID, stopChiName, stopName, stopX, stopY, offsetX, offsetY, lineColor, isExchangeStop) => {
    var mapJson;

    if (!routeMapStopID) {
        alert("更新失败，请选中站点编号!");
        return false;
    }

    // $.post("../Home/GetRouteCollect", function (data) {
    //     var item = "[" + data + "]";
    //     var data = JSON.parse(item);
    //    for(item of data){
    //        item.routePath = subLinePath(item.stopsOnRoute);
    //    }
    //     reloadSubWayLine(data);
    // })

    $.getJSON(mapJsonUrl, function (data) {
        mapJson = data;
        var subPath = "";
        if (mapJson != "") {
            var index = mapJson.findIndex(a => a.displayName == lineName);
            var stopsOnRoute = mapJson[index]?.stopsOnRoute;
            for (var i = 0; i < stopsOnRoute.length; i++) {
                if (stopsOnRoute[i].routeMapStopID === routeMapStopID) {
                    stopsOnRoute[i].name = stopChiName;
                    stopsOnRoute[i].stopChiName = stopChiName;
                    stopsOnRoute[i].stopName = stopName;
                    stopsOnRoute[i].exchangeStop = isExchangeStop;
                    stopsOnRoute[i].stopX = parseInt(stopX);
                    stopsOnRoute[i].stopY = parseInt(stopY);
                    stopsOnRoute[i].nameRight = parseInt(offsetX);
                    stopsOnRoute[i].nameTop = parseInt(offsetY);
                    break;
                }
            }

            subPath = subLinePath(stopsOnRoute);
            mapJson[index].routePath = subPath;
            mapJson[index].routeColor = lineColor.replace('#', '');
        }

        removeLocalStorage(stopName);
        reloadSubWayLine(mapJson);
        $(".panel,.stationCollection").hide();
    });
}

/**
 *  更新当前拖拽 站点坐标
 * @param {string} routeMapRDVID
 * @param {string} routeMapStopID
 * @param {int} stopX
 * @param {int} stopY
 * @returns
 */
var updateDraggerStationPosition = (lineName, routeMapStopID, stopX, stopY, oldLine) => {
    var mapJson;

    if (!mapJson) {
        var selArea = $("#selArea").val();
        switchMapJsonUrl(selArea);
    }

    if (!routeMapStopID) {
        alert("更新失败，请选中站点编号!");
        return false;
    }

    var path = stopX + " " + stopY;
    $.getJSON(mapJsonUrl, function (data) {
        mapJson = data;
        var subPath = "";
        if (mapJson != "") {
            var index = mapJson.findIndex(a => a.displayName == lineName);
            var stopsOnRoute = mapJson[index]?.stopsOnRoute;
            for (var i = 0; i < stopsOnRoute.length; i++) {
                if (stopsOnRoute[i].routeMapStopID === routeMapStopID) {
                    stopsOnRoute[i].stopX = parseInt(stopX);
                    stopsOnRoute[i].stopY = parseInt(stopY);
                    break;
                }
            }

            //subPath = "L 0 1300 L 275 1300 L 550 1300 L 900 1300 Q 900 1600 1280 1600 L 1280 1600 L 1500 1600 L 1800 1600 Q 2150 1600 2150 1400 L 2150 1400 L 2150 1400";
            //subPath = subPath.replaceAll(oldLine, path)
            //console.log(subPath)
            //mapJson[index].routePath = subPath;
        }


        zoomScale.isDrag = true;
        reloadSubWayLine(mapJson);
        subwayMap.zoomViaMouseWheel(zoomScale);
    });
}

/**
 * 添加站点
 * @param {string} lineName 线路名称
 * @param {string} routeMapStopID 编码
 * @param {string} stopChiName 名称
 * @param {string} stopName 英文名称
 * @param {int} stopX 站点 X 轴 
 * @param {int} stopY 站点 Y 轴
 * @param {int} offsetX text X 轴文字 
 * @param {int} offsetY text Y 轴文字
 * @param {boolean} isExchangeStop 是否为换乘站
 */
var addMapStation = (lineName, stopChiName, stopName, stopX, stopY, offsetX, offsetY, isExchangeStop) => {
    var mapJson;
    var addStation;

    $.ajaxSettings.async = false;
    $.getJSON("../buswayline/DBConfig.json", function (data) {
        addStation = data.station;
    })
    // $.post("../Home/GetRouteCollect", function (data) {
    //     var item = "[" + data + "]";
    //     var data = JSON.parse(item);
    //    for(item of data){
    //        item.routePath = subLinePath(item.stopsOnRoute);
    //    }
    //     reloadSubWayLine(data);
    // })
    $.getJSON(mapJsonUrl, function (data) {
        mapJson = data;
        var subPath = '';
        if (mapJson != "") {
            var index = mapJson.findIndex(a => a.displayName == lineName);
            var stopsOnRoute = mapJson[index]?.stopsOnRoute;
            var newCode;
            if (stopsOnRoute != null && stopsOnRoute.length > 0) {
                var lastCode = stopsOnRoute[stopsOnRoute.length - 1].routeMapStopID;

                newCode = mapJson[index].routeMapRDVID + ((parseInt(lastCode.replace(mapJson[index].routeMapRDVID, "")) + 1) > 10
                    ? (parseInt(lastCode.replace(mapJson[index].routeMapRDVID, "")) + 1) : "0" + (parseInt(lastCode.replace(mapJson[index].routeMapRDVID, "")) + 1));
            } else {
                newCode = mapJson[index].routeMapRDVID + "01";
            }

            addStation.routeMapStopID = newCode;
            addStation.stopX = parseInt(stopX);
            addStation.stopY = parseInt(stopY);
            addStation.stopChiName = stopChiName;
            addStation.stopName = stopName;
            addStation.exchangeStop = isExchangeStop;
            addStation.nameRight = parseInt(offsetX);
            addStation.nameTop = parseInt(offsetY);

            mapJson[index].stopsOnRoute.push(addStation);

            subPath = subLinePath(stopsOnRoute);
            mapJson[index].routePath = subPath;
        }

        if (isExchangeStop)
            removeLocalStorage(stopName);

        reloadSubWayLine(mapJson);
    })
}

/**
 * 删除指定站点
 * @param {string} lineName 线路名称
 * @param {string} routeMapStopID 站点编码
 */
var delMapStation = (lineName, routeMapStopID) => {
    if (!routeMapStopID) {
        alert("删除失败，请选中站点编号!");
        return false;
    }

    // $.post("../Home/GetRouteCollect", function (data) {
    //     var item = "[" + data + "]";
    //     var data = JSON.parse(item);
    //    for(item of data){
    //        item.routePath = subLinePath(item.stopsOnRoute);
    //    }
    //     reloadSubWayLine(data);
    // })
    $.getJSON(mapJsonUrl, function (data) {
        mapJson = data;
        var subPath = '';
        if (mapJson != "") {
            var index = mapJson.findIndex(a => a.displayName == lineName);
            var stopsOnRoute = mapJson[index].stopsOnRoute;

            var stationIndex = stopsOnRoute.reduce((r, o, i) => (o.routeMapStopID === routeMapStopID && r.push(i), r), []);
            if (stopsOnRoute[stationIndex].exchangeStop) {
                removeLocalStorage(stopsOnRoute[stationIndex].stopName);
            }
            stopsOnRoute.splice(stationIndex, 1);

            subPath = subLinePath(stopsOnRoute);
            mapJson[index].routePath = subPath;
        }

        reloadSubWayLine(mapJson);
    });
}

/**
 * 计算指定线路的站点路径曲线
 * 如果当前下一个点在上一个点之上，则曲线弧度上抛，反之则下抛，详见 Q 属性 第一个 数值，第二个数值为两个点 Y 坐标之差
 * @param {any} stopsOnRoute
 * @returns
 */
var subLinePath = (stopsOnRoute) => {
    let subPath = '';
    if (stopsOnRoute.length < 1)
        return subPath;

    var length = stopsOnRoute.length - 1; //下文判断，排除最后一个 站点，最后一个站点位置改变，不会对  路径曲线造成影响，直接直线连接
    for (var i = 0; i < stopsOnRoute.length; i++) {
        if ((length > i) && Math.abs(stopsOnRoute[i + 1].stopX - stopsOnRoute[i].stopX) >= 100 && Math.abs(stopsOnRoute[i + 1].stopY - stopsOnRoute[i].stopY) >= 100) {
            /**
             * 当前点往后还存在多个点，判断抛物线 角度（右抛还是左抛）
             * 如果当前点的 后两个点和 后一个点， X Y 轴 坐标之差，例如 第二个点的 Y 轴比 第一个点 Y 轴 大，则右抛，反之则 左抛
             * */
            if (length - i > 1 && Math.abs(stopsOnRoute[i + 2].stopX - stopsOnRoute[i + 1].stopX) < 100 && stopsOnRoute[i + 2].stopY - stopsOnRoute[i + 1].stopY >= 0) {
                /**
                 * L 1205 846 Q 1305 846 1305 946 L 1305 1046  
                 * 往下，右 抛场景，上面为列举参数
                 * **/
                subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY + " Q "
                    + stopsOnRoute[i + 1].stopX + " "
                    + stopsOnRoute[i].stopY + " "
                    + stopsOnRoute[i + 1].stopX + " "
                    + parseInt(stopsOnRoute[i].stopY + stopsOnRoute[i + 1].stopY) / 2 + "";
            }
            else {
                /**
                * L 1305 2046 Q 1305 2246 1475 2246 L 1475 2246
                * L 1800 1600 Q 2150 1600 2150 1400 L 2150 1400
                * 两种场景，第一种是 左下抛    第二种是右下抛
                * **/
                subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY + " Q "
                    + parseInt(stopsOnRoute[i].stopY > stopsOnRoute[i + 1].stopY ? stopsOnRoute[i + 1].stopX : stopsOnRoute[i].stopX) + " "
                    + (parseInt((stopsOnRoute[i].stopY + stopsOnRoute[i + 1].stopY) / 2) + (Math.abs(stopsOnRoute[i + 1].stopY - stopsOnRoute[i].stopY) > 200 ? 150 : 100)) + " "
                    + stopsOnRoute[i + 1].stopX + " "
                    + stopsOnRoute[i + 1].stopY + "";
            }
        } else {
            subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY;
        }
    }
    console.log(subPath);
    return subPath;
}

/**
 * 绘制部分站点线路曲线
 * @param {any} stopsOnRoute
 * @returns
 */
var graphSubLineStopPath = (stopsOnRoute) => {
    let subPath = '';
    if (stopsOnRoute.length < 1)
        return subPath;

    var length = stopsOnRoute.length - 1; //下文判断，排除最后一个 站点，最后一个站点位置改变，不会对  路径曲线造成影响，直接直线连接
    for (var i = 0; i < stopsOnRoute.length - 1; i++) {
        if ((length > i) && Math.abs(stopsOnRoute[i + 1].stopX - stopsOnRoute[i].stopX) >= 100 && Math.abs(stopsOnRoute[i + 1].stopY - stopsOnRoute[i].stopY) >= 100) {
            /**
             * 当前点往后还存在多个点，判断抛物线 角度（右抛还是左抛）
             * 如果当前点的 后两个点和 后一个点， X Y 轴 坐标之差，例如 第二个点的 Y 轴比 第一个点 Y 轴 大，则右抛，反之则 左抛
             * */
            if (length - i > 1 && Math.abs(stopsOnRoute[i + 2].stopX - stopsOnRoute[i + 1].stopX) < 100 && stopsOnRoute[i + 2].stopY - stopsOnRoute[i + 1].stopY >= 0) {
                /**
                 * L 1205 846 Q 1305 846 1305 946 L 1305 1046  
                 * 往下，右 抛场景，上面为列举参数
                 * **/
                subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY + " Q "
                    + stopsOnRoute[i + 1].stopX + " "
                    + stopsOnRoute[i].stopY + " "
                    + stopsOnRoute[i + 1].stopX + " "
                    + parseInt(stopsOnRoute[i].stopY + stopsOnRoute[i + 1].stopY) / 2 + "";
            }
            else {
                /**
                * L 1305 2046 Q 1305 2246 1475 2246 L 1475 2246
                * L 1800 1600 Q 2150 1600 2150 1400 L 2150 1400
                * 两种场景，第一种是 左下抛    第二种是右下抛
                * **/
                subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY + " Q "
                    + parseInt(stopsOnRoute[i].stopY > stopsOnRoute[i + 1].stopY ? stopsOnRoute[i + 1].stopX : stopsOnRoute[i].stopX) + " "
                    + (parseInt((stopsOnRoute[i].stopY + stopsOnRoute[i + 1].stopY) / 2) + (Math.abs(stopsOnRoute[i + 1].stopY - stopsOnRoute[i].stopY) > 200 ? 150 : 100)) + " "
                    + stopsOnRoute[i + 1].stopX + " "
                    + stopsOnRoute[i + 1].stopY + "";
            }
        } else {
            subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY;
        }
    }
    subPath += " L " + stopsOnRoute[length].stopX + " " + stopsOnRoute[length].stopY;
    return subPath;
}

/**
 * 绘制部分站点线路直角
 * @param {any} stopsOnRoute
 * @returns
 */
var rightAngleSubLineStopPath = (stopsOnRoute) => {
    let subPath = '';
    if (stopsOnRoute.length < 1)
        return subPath;

    var length = stopsOnRoute.length - 1; //下文判断，排除最后一个 站点，最后一个站点位置改变，不会对  路径曲线造成影响，直接直线连接
    var i = 0;
    if (length - i > 1) {
        if ((stopsOnRoute[i + 2].stopY - stopsOnRoute[i + 1].stopY > 0) && (Math.abs(stopsOnRoute[i + 2].stopX - stopsOnRoute[i + 1].stopX) <= 100)) {
            /**
             * 下面第二个点点还在下面，或者在上面
             * 开口角度往 右下/右上 垂直
             */
            subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY + " L "
                + stopsOnRoute[i + 1].stopX + " "
                + stopsOnRoute[i].stopY + " " + "L "
                + stopsOnRoute[i + 1].stopX + " "
                + stopsOnRoute[i + 1].stopY + " ";
        }
        else if ((stopsOnRoute[i + 2].stopX - stopsOnRoute[i + 1].stopX > 0) && (Math.abs(stopsOnRoute[i + 2].stopY - stopsOnRoute[i + 1].stopY) <= 100)) {
            // 左下/ 左上 垂直
            subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY + " L "
                + stopsOnRoute[i].stopX + " "
                + stopsOnRoute[i + 1].stopY + " " + "L "
                + stopsOnRoute[i + 1].stopX + " "
                + stopsOnRoute[i + 1].stopY + " ";
        }
    } else {
        if (stopsOnRoute[i + 1].stopX > stopsOnRoute[i].stopX > 0 && stopsOnRoute[i + 1].stopY < stopsOnRoute[i].stopY) {
            subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY + " L "
                + stopsOnRoute[i + 1].stopX + " "
                + stopsOnRoute[i].stopY + "";
        } else {
            subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY + " L "
                + stopsOnRoute[i].stopX + " "
                + stopsOnRoute[i + 1].stopY + "";
        }
    }
    subPath += " L " + stopsOnRoute[length].stopX + " " + stopsOnRoute[length].stopY;

    return subPath;
}

/**
 * 绘制部分站点线路 直线
 * @param {any} stopsOnRoute
 * @returns
 */
var straightSubLineStopPath = (stopsOnRoute) => {
    let subPath = '';
    if (stopsOnRoute.length < 1)
        return subPath;

    for (var i = 0; i < stopsOnRoute.length; i++) {
        subPath += " L " + stopsOnRoute[i].stopX + " " + stopsOnRoute[i].stopY;
    }
    return subPath;
}

/**
 * 切换线路 区域
 * @param {any} selArea
 */
var switchLineArea = (selArea) => {
    switchMapJsonUrl(selArea);

    // $.post("../Home/GetRouteCollect", function (data) {
    //     var item = "[" + data + "]";
    //     var data = JSON.parse(item);
    //    for(item of data){
    //        item.routePath = subLinePath(item.stopsOnRoute);
    //    }
    //     reloadSubWayLine(data);
    // })
    $.getJSON(mapJsonUrl, function (data) {
        reloadSubWayLine(data);
    })
}

/**
 * 重新加载 线路图
 * @param {any} mapJson
 */
var reloadSubWayLine = (mapJson) => {
    if (!mapJson) {
        alert("暂无线路站点信息!");
        return false;
    }
    Subwaymap.actualWidth = 0; Subwaymap.actualHeight = 0; Subwaymap.minWidth = 0; Subwaymap.minHeight = 0;
    subwayMap = new Subwaymap({
        containerId: "subwayMap",
        mapJson: mapJson,
        type: "init_load"
    });
    var width = $(window).width();
    var height = $(window).height();
    subwayMap.updateUI(width, height);

    // 此方法 用于加载 页面时， 显示 对应的 Bus 图标，此处需要延迟加载
    setTimeout(function () {
        exchangeStopLayer();
    }, 500);
}

/**
 * 地图缩放操作
 * @param {int} num  区分 放大/缩小 场景  +1 / -1
 */
var mapZoom = (num) => {
    var scale = num;
    var width = $(window).width();
    var height = $(window).height();
    var e =
    {
        offsetX: parseInt(width / 2),
        offsetY: parseInt(height / 2),
        originalEvent: {
            wheelDelta: scale,
            detail: 0
        }
    }
    let element = document.querySelector('.backimg'); // 选择具有该类的第一个元素
    let style = window.getComputedStyle(element); // 获取计算后的样式
    let backgroundSize = style.getPropertyValue('background-size');
    let first = parseInt(backgroundSize.split(' ')[0].replace("%", ""));
    let second = parseInt(backgroundSize.split(' ')[1].replace("%", ""));
    if (num > 0) {
        first += 18;
        second += 5;
        val = first + "% " + second + "%";
    } else {
        first -= 18;
        second -= 5;
    }
   
    if (first < 100 || second < 100)
        return false;

    val = first + "% " + second + "%";
    $(".backimg").css({ "background-size": val });
    subwayMap.zoomViaMouseWheel(e);
}

/**
 * 设置元素可拖拽操作
 * @param {any} element
 */

var elementDraggable = (element) => {
    var move = document.getElementById(element).parentElement;
    move.addEventListener('mousedown', function (event) {
        if (!panelMove) {
            return false;
        }
        var disx = event.clientX - move.offsetLeft;
        var disy = event.clientY - move.offsetTop
        document.onmousemove = function (event) {
            move.style.left = event.clientX - disx + 'px';
            move.style.top = event.clientY - disy + 'px';
        }
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
            return false;
        }
    })
}

var postionX = 0;
var postionY = 1300;

/**
 * 刷新 bus 位置
 */
var reloadBusLocation = () => {
    var stage = subwayMap.stage;
    stage.getChildren().forEach(function (layer) {
        if (layer instanceof Kinetic.Layer) {

            if (layer.attrs.id == "stationlayer")
                return;

            if (layer.attrs.id.indexOf("Buslinelayer_") >= 0) {
                var children = layer.getChildren();
                var busGroupCode = "BusGroup0301";
                /**
                 * 当我们再次添加 相同编号的 Bus时，集合中会存在两个 bus 对应的 Group，此时，我们需要获取到其索引，然后先从 container 中删除
                 * 如下循环所示，根据索引删除 container 中的 数据
                 * 值得注意的是，所以每次删除，对应的 container 中索引也会跟着动态改变，才会有 下文中的 stationIndex[i] - 1  这个操作
                 */
                var stationIndex = layer.children.reduce((r, o, i) => (o.attrs?.type === "Bus" && r.push(i), r), []).sort((a, b) => b - a);
                for (var i = 0; i < stationIndex.length; i++) {
                    layer.children.splice(stationIndex[i], 1);
                }

                //for (var i = 0; i < children.length; i++) {
                //    const currentStation = layer.children[i];

                //    // 修改 Bus 位置，需要判断当前点位置和下一个点位置
                //    currentStation.attrs.line.stopsOnRoute[0].x = postionX;
                //    currentStation.attrs.line.stopsOnRoute[0].y = postionY;

                //    const station = {
                //        stopX: postionX,
                //        stopY: postionY,
                //        routeMapStopID: currentStation.attrs.line.stopsOnRoute[0].routeMapStopID
                //    };
                //    new Subwaymap.SingleBusLines(layer, currentStation.attrs.line, station);
                //    postionX = postionX + 20;
                //    break;
                //}

                // 修改 Bus 位置，需要判断当前点位置和下一个点位置
                const currentStation = layer.attrs.line;
                currentStation.stopsOnRoute[0].stopX = postionX;
                currentStation.stopsOnRoute[0].stopY = postionY;

                const station = {
                    stopX: postionX,
                    stopY: postionY,
                    routeMapStopID: currentStation.stopsOnRoute[0].routeMapStopID
                };
                new Subwaymap.SingleBusLines(layer, currentStation, station);
            }
        }
    });

    stage.draw();
}

/**
 * 添加一个 Bus
 */
var addCurrentBus = () => {
    var stage = subwayMap.stage;
    stage.getChildren().forEach(function (layer) {
        if (layer instanceof Kinetic.Layer) {
            /**
             * 所有的 Bus 绘画根据指定的 line code 进行绘制，每条线路的 Bus 相对独立
             */
            if (layer.attrs.id == "linelayer_03") {
                currentStation = layer.attrs.line;
                if (currentStation != null) {
                    currentStation.stopsOnRoute[0].x = 0;
                    currentStation.stopsOnRoute[0].y = 1300;
                    const station = {
                        stopX: 0,
                        stopY: 1300,
                        routeMapStopID: currentStation.stopsOnRoute[0].routeMapStopID
                    };
                    new Subwaymap.BusLines(layer, currentStation, station);
                }
            }

            if (layer.attrs.id == "linelayer_01") {
                currentStation = layer.attrs.line;
                if (currentStation != null) {
                    currentStation.stopsOnRoute[0].x = 405;
                    currentStation.stopsOnRoute[0].y = 86;
                    const station = {
                        stopX: 405,
                        stopY: 86,
                        routeMapStopID: currentStation.stopsOnRoute[0].routeMapStopID
                    };
                    new Subwaymap.BusLines(layer, currentStation, station);
                }
            }
        }
    });

    stage.draw();
}

/**
 * 显示换乘站图标
 */
var exchangeStopLayer = () => {
    var stage = subwayMap.stage;
    var mapJson = "";
    var exchangeStop = [];
    stage.getChildren().forEach(function (layer) {
        if (layer instanceof Kinetic.Layer) {

            if (layer.attrs.id == "stationlayer") {
                $.ajaxSettings.async = false;
                $.getJSON(mapJsonUrl, function (data) {
                    mapJson = data;
                    for (item of mapJson) {
                        for (subitem of item.stopsOnRoute) {
                            if (subitem.exchangeStop)
                                exchangeStop.push(subitem);
                        }
                    }
                })

                if (exchangeStop != null && exchangeStop.length > 0) {
                    drawExchangeStop(layer, exchangeStop);
                }
            }
        }
    });

    stage.draw();
}


var drawExchangeStop = (layer, exchangeStop) => {
    const groupedItems = groupBy(exchangeStop, 'stopName');
    var stopList = [];
    Object.keys(groupedItems).forEach(stopName => {
        groupedItems[stopName].forEach(item => {
            stopList.push(item);
        });
        stopList.sort(function (a, b) {
            return a.stopX - b.stopX;
        });
        new Subwaymap.ExchangeStopLayer(layer, stopList);
        stopList = [];
    });
}

var groupBy = (array, key) => {
    return array.reduce((result, currentItem) => {
        const groupKey = typeof key === 'function' ? key(currentItem) : currentItem[key];
        if (!result[groupKey]) {
            result[groupKey] = [];
        }
        result[groupKey].push(currentItem);
        return result;
    }, {});
};

//setInterval(function () {
//    reloadBusLocation();
//}, 10000);

/**
 * 线路车站列表
 * @param {any} currentLine
 */
var stationCollection = (currentLine) => {
    $(".stationCollection>ul").empty();
    $(".stationCollection").show();
    let html = '';
    for (var i = 0; i < currentLine.stopsOnRoute.length; i++) {
        html += "<li draggable='true' " + (currentLine.stopsOnRoute[i].virtualStop ? "class='singleVirtualStaion'" : "") + " lineName=" + currentLine.displayName + " routeMapRDVID = " + currentLine.routeMapRDVID + "  stopChiName = " + currentLine.stopsOnRoute[i].stopChiName + " routeMapStopID = " + currentLine.stopsOnRoute[i].routeMapStopID + " > "
            + currentLine.stopsOnRoute[i].stopChiName +
            "</li>";
    }

    $(".stationCollection>ul").append(html);

    // 执行拖拽操作
    const list = document.querySelector('.list');
    let currentLi;
    list.addEventListener('dragstart', e => {
        e.dataTransfer.effectAllowed = 'move';
        currentLi = e.target;
        // 异步设置样式为空白 不异步会导致鼠标拖拽中的样式也会变
        setTimeout(() => {
            currentLi.classList.add('moving');
        })
    })
    list.addEventListener('dragenter', e => {
        e.preventDefault();
        if (e.target === currentLi || e.target === list) {
            return;
        }
        const liArray = Array.from(list.childNodes);
        const currentIndex = liArray.indexOf(currentLi);
        const targetindex = liArray.indexOf(e.target);
        if (currentIndex < targetindex) {
            list.insertBefore(currentLi, e.target.nextElementSibling);
        } else {
            list.insertBefore(currentLi, e.target);
        }
    })
    list.addEventListener('dragover', e => {
        e.preventDefault();
    })
    list.addEventListener('dragend', e => {
        currentLi.classList.remove('moving');
    })
}

/**
 * 保存拖拽之后的站点
 */
var saveStationList = () => {
    const list = $(".stationCollection>ul>li");
    let lineName = list[0].getAttribute("lineName");
    for (var i = 0; i < list.length; i++) {
        let name = list[i];
        let routeMapRDVID = name.getAttribute("routeMapRDVID");
        let stopChiName = name.getAttribute("stopChiName");
        let routeMapStopID = name.getAttribute("routeMapStopID");
        console.log(lineName + " " + routeMapRDVID + " " + stopChiName + " " + routeMapStopID + " " + (i + 1));
    }
    //$.getJSON(mapJsonUrl, function (data) {
    //    mapJson = data;
    //    var subPath = '';
    //    if (mapJson != "") {
    //        var currentLine = mapJson.filter(a => a.displayName == lineName);
    //        var index = mapJson.findIndex(a => a.displayName == lineName);
    //        var stopsOnRoute = currentLine[0].stopsOnRoute;

    //        mapJson[index].stopsOnRoute.push(addStation);

    //        subPath = subLinePath(stopsOnRoute);
    //        mapJson[index].routePath = subPath;
    //    }

    //    reloadSubWayLine(mapJson);
    //})
}

/**
 * 添加指定线路的虚拟站点
 * @param {string} lineName
 * @param {int} stopX
 * @param {int} stopY
 * @returns
 */
var addLineVirtualStation = (lineName, stopX, stopY) => {
    var stopChiName = "虚拟站点";
    var mapJson;
    var addStation;

    if (!stopX || !stopY) {
        alert("请输入坐标参数信息!");
        return false;
    }

    $.ajaxSettings.async = false;
    $.getJSON("../buswayline/DBConfig.json", function (data) {
        addStation = data.station;
    })
    $.getJSON(mapJsonUrl, function (data) {
        mapJson = data;
        var subPath = '';
        if (mapJson != "") {
            var currentLine = mapJson.filter(a => a.displayName == lineName);
            var index = mapJson.findIndex(a => a.displayName == lineName);
            var stopsOnRoute = currentLine[0].stopsOnRoute;
            var newCode;
            if (stopsOnRoute != null && stopsOnRoute.length > 0) {
                var lastCode = stopsOnRoute[stopsOnRoute.length - 1].routeMapStopID;

                newCode = mapJson[index].routeMapRDVID + ((parseInt(lastCode.replace(mapJson[index].routeMapRDVID, "")) + 1) > 10
                    ? (parseInt(lastCode.replace(mapJson[index].routeMapRDVID, "")) + 1) : "0" + (parseInt(lastCode.replace(mapJson[index].routeMapRDVID, "")) + 1));
            } else {
                newCode = mapJson[index].routeMapRDVID + "01";
            }

            addStation.routeMapStopID = newCode;
            addStation.stopX = parseInt(stopX);
            addStation.stopY = parseInt(stopY);
            addStation.stopChiName = stopChiName;
            addStation.englishText = "";
            addStation.virtualStop = true;
            addStation.nameRight = 0;
            addStation.nameTop = 0;

            mapJson[index].stopsOnRoute.push(addStation);

            subPath = subLinePath(stopsOnRoute);
            mapJson[index].routePath = subPath;
        }

        reloadSubWayLine(mapJson);
        $(".virtualStop").hide();
    })
}

/**
 * 添加任意车站
 * @param {string} lineName 线路名称
 * @param {string} stopChiName 名称
 * @param {string} stopName 英文名称
 * @param {int} stopX 站点 X 轴 
 * @param {int} stopY 站点 Y 轴
 * @param {int} offsetX text X 轴文字 
 * @param {int} offsetY text Y 轴文字
 * @param {boolean} isExchangeStop 是否为换乘站
 */
var addLineArbitrarilyStation = (lineName, stopChiName, stopName, stopX, stopY, offsetX, offsetY, isExchangeStop) => {
    var mapJson;
    var addStation;

    if (!stopChiName || !stopName || !stopX || !stopY || !offsetX || !offsetY) {
        alert("所有信息必填!");
        return false;
    }

    $.ajaxSettings.async = false;
    $.getJSON("../buswayline/DBConfig.json", function (data) {
        addStation = data.station;
    })
    $.getJSON(mapJsonUrl, function (data) {
        mapJson = data;
        var subPath = '';
        if (mapJson != "") {
            var index = mapJson.findIndex(a => a.displayName == lineName);
            var stopsOnRoute = mapJson[index]?.stopsOnRoute;
            var newCode;
            if (stopsOnRoute != null && stopsOnRoute.length > 0) {
                var lastCode = stopsOnRoute[stopsOnRoute.length - 1].routeMapStopID;

                newCode = mapJson[index].routeMapRDVID + ((parseInt(lastCode.replace(mapJson[index].routeMapRDVID, "")) + 1) > 10
                    ? (parseInt(lastCode.replace(mapJson[index].routeMapRDVID, "")) + 1) : "0" + (parseInt(lastCode.replace(mapJson[index].routeMapRDVID, "")) + 1));
            } else {
                newCode = mapJson[index].routeMapRDVID + "01";
            }

            addStation.routeMapStopID = newCode;
            addStation.stopX = parseInt(stopX);
            addStation.stopY = parseInt(stopY);
            addStation.stopChiName = stopChiName;
            addStation.stopName = stopName;
            addStation.virtualStop = false;
            addStation.exchangeStop = isExchangeStop;
            addStation.nameRight = parseInt(offsetX ?? 0);
            addStation.nameTop = parseInt(offsetY ?? 0);

            mapJson[index].stopsOnRoute.push(addStation);

            subPath = subLinePath(stopsOnRoute);
            mapJson[index].routePath = subPath;
        }

        $(".arbitrarilyStation").hide();
        if (isExchangeStop)
            removeLocalStorage(stopName);

        reloadSubWayLine(mapJson);
    })
}

/**
 * 公共线路路线绘画
 * @param {any} stopsOnRoute
 * @returns
 */
var publicStopListPath = (stopsOnRoute) => {
    var routePath = "";
    var list = [];
    var list_stopsOnRoute = stopsOnRoute;
    for (let i = 0; i < list_stopsOnRoute.length; i++) {
        if (!list_stopsOnRoute[i].publishedStop || (list_stopsOnRoute.length - 1 > i && list_stopsOnRoute[i].publishedStop && !list_stopsOnRoute[i].publishedLine)) {
            list.push(list_stopsOnRoute[i]);
        } else if (i > 0 && !list_stopsOnRoute[i - 1].publishedStop && list_stopsOnRoute[i].publishedStop) {
            list.push(list_stopsOnRoute[i]);
        } else if (list_stopsOnRoute[i].publishedStop && (i + 1) < list_stopsOnRoute.length && !list_stopsOnRoute[i + 1].publishedStop) {
            list.push(list_stopsOnRoute[i]);
        } else if (list_stopsOnRoute[i].publishedStop && list_stopsOnRoute[i].publishedLine && i > 0 && !list_stopsOnRoute[i - 1].publishedLine) {
            list.push(list_stopsOnRoute[i]);
        } else if (i > 0 && list_stopsOnRoute[i].publishedStop && !list_stopsOnRoute[i].publishedLine && !list_stopsOnRoute[i - 1].publishedLine && list_stopsOnRoute[i - 1].publishedStop) {
            list.push(list_stopsOnRoute[i]);
        }
    }
    if (list.length == 2) {
        routePath += " L " + list[0].stopX + " " + list[0].stopY + " L " + list[1].stopX + " " + list[1].stopY;
    } else {
        for (let i = 0; i < list.length; i++) {
            if (list[i].publishedStop && (i + 1) < list.length && list[i + 1].publishedStop) {
                routePath += " L " + list[i].stopX + " " + list[i].stopY + " M " + list[i + 1].stopX + " " + list[i + 1].stopY;
            } else if (list[i].publishedStop && list.length == 2 && (i + 1) < list.length && !list[i + 1].publishedStop) {
                routePath += " L " + list[i].stopX + " " + list[i].stopY;
            } else if (!list[i].publishedStop && (i + 1) < list.length && list[i + 1].publishedStop) {
                routePath += " L " + list[i].stopX + " " + list[i].stopY;
            } else if (list[i].publishedStop && i > 0 && !list[i - 1].publishedStop) {
                routePath += " L " + list[i].stopX + " " + list[i].stopY;
            } else if (!list[i].publishedStop) {
                routePath += " L " + list[i].stopX + " " + list[i].stopY;
            } else if (list[i].publishedStop && !list[i].publishedLine && (i > 0 ? !list[i - 1].publishedLine : true) && (i + 1) < list.length && !list[i + 1].publishedStop) {
                routePath += " L " + list[i].stopX + " " + list[i].stopY;
            }
        }
    }


    console.log(routePath)
    return routePath;
}

/**
 * 设置cookie 缓存
 * @param {string} cname 缓存 key
 * @param {string} cvalue 缓存 值
 * @param {int} exdays 缓存 时间（天）
 */
var setCookie = (cname, cvalue, exdays) => {
    var d = new Date();
    d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
    var expires = 'expires=' + d.toGMTString();
    document.cookie = cname + '=' + cvalue + ';' + expires;
}

/**
 * 获取缓存值
 * @param {string} cname 缓存 key
 * @returns
 */
var getCookie = (cname) => {
    var name = cname + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        if (ca[i].indexOf(name) >= 0) {
            return ca[i].split('=')[1];
        }
    }
    return '';
}

/**
 * 清除cookie 
 * @param {string} name 缓存 key
 */
var clearCookie = (name) => {
    setCookie(name, "", -1);
}

/**
 * 设置 localStorage 存储
 * @param {string} cname
 * @param {string} cvalue
 */
var setLocalStorage = (cname, cvalue) => {
    localStorage.setItem(cname, cvalue);
}

/**
 * 获取 指定的 localStorage 值
 * @param {string} cname
 * @returns
 */
var getLocalStorage = (cname) => {
    var value = localStorage.getItem(cname);
    return value;
}

/**
 * 删除指定的 localStorage 值
 * @param {string} cname
 */
var removeLocalStorage = (cname) => {
    localStorage.removeItem(cname);
}

/**
 * 切换 地图 json 文件
 * @param {any} num
 * @returns
 */
var switchMapJsonUrl = (num) => {
    switch (num) {
        case "1":
            mapJsonUrl = "../buswayline/map.json";
            break;
        case "2":
            mapJsonUrl = "../buswayline/maptest.json";
            break;
        default:
            mapJsonUrl = "../buswayline/map.json";
            break;
    }
}